<template>
  <el-dialog
    v-model="dialogVisible"
    title="打印预览"
    width="900px"
    :before-close="handleClose"
    top="5vh"
  >
    <div class="print-preview-dialog">
      <!-- 打印设置 -->
      <div class="print-settings">
        <el-form :model="printForm" inline>
          <el-form-item label="纸张方向">
            <el-radio-group v-model="printForm.orientation">
              <el-radio-button label="portrait">纵向</el-radio-button>
              <el-radio-button label="landscape">横向</el-radio-button>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="纸张尺寸">
            <el-select v-model="printForm.paperSize" style="width: 150px">
              <el-option label="A4" value="a4" />
              <el-option label="A3" value="a3" />
              <el-option label="Letter" value="letter" />
            </el-select>
          </el-form-item>

          <el-form-item label="边距">
            <el-select v-model="printForm.margin" style="width: 120px">
              <el-option label="默认" value="default" />
              <el-option label="窄" value="narrow" />
              <el-option label="宽" value="wide" />
            </el-select>
          </el-form-item>

          <el-form-item label="显示选项">
            <el-checkbox-group v-model="printForm.options">
              <el-checkbox label="header">表头</el-checkbox>
              <el-checkbox label="footer">页脚</el-checkbox>
              <el-checkbox label="summary">统计信息</el-checkbox>
              <el-checkbox label="ranking">排名</el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handlePrint">
              <el-icon><Printer /></el-icon> 打印
            </el-button>
            <el-button @click="handleExportPDF">
              <el-icon><Document /></el-icon> 导出PDF
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 预览区域 -->
      <div class="preview-container">
        <div class="preview-wrapper" :class="`orientation-${printForm.orientation}`">
          <div class="preview-content" ref="printContentRef">
            <!-- 打印表头 -->
            <div v-if="printForm.options.includes('header')" class="print-header">
              <div class="header-content">
                <div class="school-info">
                  <h1 class="school-name">校园运动会成绩单</h1>
                  <p class="print-date">打印日期：{{ formatDate(new Date()) }}</p>
                </div>
                <div class="print-stats">
                  <div class="stat-item">
                    <span class="stat-label">总记录数：</span>
                    <span class="stat-value">{{ scores.length }}</span>
                  </div>
                  <div class="stat-item">
                    <span class="stat-label">生成时间：</span>
                    <span class="stat-value">{{ formatDateTime(new Date()) }}</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 统计信息 -->
            <div v-if="printForm.options.includes('summary')" class="print-summary">
              <h3 class="summary-title">成绩统计</h3>
              <div class="summary-cards">
                <div class="summary-card">
                  <div class="card-label">已公示</div>
                  <div class="card-value">{{ getStatisticsCount('PUBLISHED') }}</div>
                </div>
                <div class="summary-card">
                  <div class="card-label">待审核</div>
                  <div class="card-value">{{ getStatisticsCount('PENDING') }}</div>
                </div>
                <div class="summary-card">
                  <div class="card-label">已驳回</div>
                  <div class="card-value">{{ getStatisticsCount('REJECTED') }}</div>
                </div>
                <div class="summary-card">
                  <div class="card-label">有异议</div>
                  <div class="card-value">{{ getStatisticsCount('DISPUTED') }}</div>
                </div>
              </div>
            </div>

            <!-- 成绩表格 -->
            <div class="print-table">
              <table class="score-table">
                <thead>
                  <tr>
                    <th v-if="printForm.options.includes('ranking')">排名</th>
                    <th>项目</th>
                    <th>学生姓名</th>
                    <th>学号</th>
                    <th>学院</th>
                    <th>成绩</th>
                    <th>轮次</th>
                    <th>状态</th>
                    <th>提交时间</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(item, index) in scores" :key="item.id || index">
                    <td v-if="printForm.options.includes('ranking')" class="ranking-cell">
                      <span v-if="item.rank <= 3" class="medal">{{ getMedalIcon(item.rank) }}</span>
                      <span v-else>{{ item.rank || '-' }}</span>
                    </td>
                    <td>{{ item.project?.name || '-' }}</td>
                    <td>{{ item.student?.name || '-' }}</td>
                    <td>{{ item.student?.studentNumber || '-' }}</td>
                    <td>{{ item.student?.department || '-' }}</td>
                    <td class="score-cell">
                      <span :class="{ 'record-breaking': item.isRecord }">
                        {{ item.score || '-' }}{{ item.unit || '' }}
                      </span>
                      <span v-if="item.isRecord" class="record-label">(破纪录)</span>
                    </td>
                    <td>{{ getRoundText(item.round) }}</td>
                    <td>
                      <span class="status-badge" :class="getStatusClass(item.status)">
                        {{ getStatusText(item.status) }}
                      </span>
                    </td>
                    <td>{{ formatDateTime(item.createTime) }}</td>
                  </tr>
                </tbody>
              </table>
            </div>

            <!-- 打印页脚 -->
            <div v-if="printForm.options.includes('footer')" class="print-footer">
              <div class="footer-content">
                <div class="footer-info">
                  <span>第 1 页，共 {{ totalPages }} 页</span>
                </div>
                <div class="footer-seal">
                  <span>运动会组委会</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handlePrint">
          <el-icon><Printer /></el-icon> 打印
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Printer, Document } from '@element-plus/icons-vue'

// 组件属性
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  scores: {
    type: Array,
    default: () => []
  }
})

// 组件事件
const emit = defineEmits(['update:modelValue', 'close', 'print'])

// 对话框可见性
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 打印内容引用
const printContentRef = ref(null)

// 总页数
const totalPages = ref(1)

// 打印表单
const printForm = reactive({
  orientation: 'portrait',
  paperSize: 'a4',
  margin: 'default',
  options: ['header', 'footer', 'ranking']
})

// 获取奖牌图标
const getMedalIcon = (rank) => {
  if (rank === 1) return '🥇'
  if (rank === 2) return '🥈'
  if (rank === 3) return '🥉'
  return ''
}

// 获取轮次文本
const getRoundText = (round) => {
  const roundMap = {
    1: '第1轮',
    2: '第2轮',
    3: '第3轮',
    4: '决赛'
  }
  return roundMap[round] || '-'
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    'PENDING': '待审核',
    'PUBLISHED': '已公示',
    'REJECTED': '已驳回',
    'DISPUTED': '有异议'
  }
  return textMap[status] || '-'
}

// 获取状态样式类
const getStatusClass = (status) => {
  const classMap = {
    'PENDING': 'pending',
    'PUBLISHED': 'published',
    'REJECTED': 'rejected',
    'DISPUTED': 'disputed'
  }
  return classMap[status] || ''
}

// 获取统计数量
const getStatisticsCount = (status) => {
  return props.scores.filter(item => item.status === status).length
}

// 格式化日期
const formatDate = (date) => {
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 处理打印
const handlePrint = () => {
  // 创建打印样式
  const printStyles = `
    <style>
      @media print {
        body * {
          visibility: hidden;
        }
        .print-content, .print-content * {
          visibility: visible;
        }
        .print-content {
          position: absolute;
          left: 0;
          top: 0;
          width: 100%;
        }
        @page {
          size: ${printForm.paperSize} ${printForm.orientation};
          margin: ${getPrintMargin()};
        }
      }
    </style>
  `

  // 添加打印样式到页面
  const styleElement = document.createElement('style')
  styleElement.innerHTML = printStyles.replace('@media print {', '').replace('}', '')
  document.head.appendChild(styleElement)

  // 打印
  window.print()

  // 移除样式
  setTimeout(() => {
    document.head.removeChild(styleElement)
  }, 1000)

  ElMessage.success('打印任务已发送')
  emit('print')
}

// 获取打印边距
const getPrintMargin = () => {
  const marginMap = {
    default: '20mm',
    narrow: '10mm',
    wide: '30mm'
  }
  return marginMap[printForm.margin] || '20mm'
}

// 导出PDF
const handleExportPDF = () => {
  ElMessage.info('PDF导出功能开发中...')
}

// 处理关闭
const handleClose = () => {
  dialogVisible.value = false
  emit('close')
}
</script>

<style scoped>
.print-preview-dialog {
  max-height: 90vh;
  overflow-y: auto;
}

/* 打印设置 */
.print-settings {
  background-color: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 20px;
  border: 1px solid #e4e7ed;
}

/* 预览容器 */
.preview-container {
  background-color: #f5f5f5;
  padding: 20px;
  border-radius: 8px;
  overflow: auto;
  max-height: 70vh;
}

.preview-wrapper {
  background-color: white;
  margin: 0 auto;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.orientation-portrait {
  width: 210mm;
  min-height: 297mm;
}

.orientation-landscape {
  width: 297mm;
  min-height: 210mm;
}

.preview-content {
  padding: 20mm;
  font-family: 'SimSun', '宋体', serif;
  color: #000;
}

/* 打印表头 */
.print-header {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #333;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
}

.school-name {
  font-size: 24px;
  font-weight: bold;
  margin: 0 0 8px 0;
  text-align: center;
}

.print-date {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.print-stats {
  display: flex;
  flex-direction: column;
  gap: 4px;
  font-size: 12px;
  color: #666;
}

.stat-item {
  display: flex;
  gap: 4px;
}

.stat-label {
  font-weight: normal;
}

.stat-value {
  font-weight: bold;
}

/* 统计信息 */
.print-summary {
  margin-bottom: 20px;
}

.summary-title {
  font-size: 18px;
  font-weight: bold;
  margin: 0 0 12px 0;
  color: #333;
}

.summary-cards {
  display: flex;
  gap: 16px;
}

.summary-card {
  background-color: #f8f9fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 12px;
  text-align: center;
  min-width: 80px;
}

.card-label {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.card-value {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

/* 成绩表格 */
.print-table {
  margin-bottom: 20px;
}

.score-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 12px;
}

.score-table th,
.score-table td {
  border: 1px solid #333;
  padding: 8px;
  text-align: left;
}

.score-table th {
  background-color: #f8f9fa;
  font-weight: bold;
  color: #333;
}

.score-table tr:nth-child(even) {
  background-color: #f8f9fa;
}

.ranking-cell {
  text-align: center;
  font-weight: bold;
}

.medal {
  font-size: 16px;
}

.score-cell {
  font-weight: bold;
}

.record-breaking {
  color: #e74c3c;
}

.record-label {
  color: #e74c3c;
  font-size: 10px;
}

.status-badge {
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 10px;
  font-weight: bold;
}

.status-badge.pending {
  background-color: #fff3cd;
  color: #856404;
}

.status-badge.published {
  background-color: #d4edda;
  color: #155724;
}

.status-badge.rejected {
  background-color: #f8d7da;
  color: #721c24;
}

.status-badge.disputed {
  background-color: #d1ecf1;
  color: #0c5460;
}

/* 打印页脚 */
.print-footer {
  margin-top: 20px;
  padding-top: 10px;
  border-top: 1px solid #333;
  font-size: 12px;
  color: #666;
}

.footer-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 对话框页脚 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .orientation-portrait {
    width: 180mm;
    min-height: 254mm;
  }

  .orientation-landscape {
    width: 254mm;
    min-height: 180mm;
  }
}

@media (max-width: 768px) {
  .print-settings .el-form {
    flex-direction: column;
    align-items: flex-start;
  }

  .header-content {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }

  .summary-cards {
    flex-wrap: wrap;
  }

  .preview-wrapper {
    transform: scale(0.8);
    transform-origin: top left;
  }
}
</style>